import torch


class Perceptron:

    def __init__(self, input_num, activator):
        """
        初始化感知器，设置输入参数的个数，以及激活函数
        激活函数的类型为double -> double
        """
        self.activator = activator
        # 权重初始化为0
        self.weights = torch.randn(input_num)# torch.tensor([0.0 for _ in range(input_num)], dtype=torch.float)
        print(f"self.weights:{self.weights}")
        # 偏置项初始化为0
        self.bias = torch.randn(1)

    def __str__(self):
        """
        打印学习到的权重、偏置项
        """
        return f'weights\t:{self.weights}\nbias\t:{self.bias}\n'

    def predict(self, input_vec):
        """
        输入向量，输出感知器的计算结果
        """
        Z = torch.sum(input_vec * self.weights + self.bias)
        output = self.activator(Z)
        return output

    def _update_weights(self, input_vec, output, label, rate):
        delta = label - output
        # 更新权重
        self.weights += rate * torch.mul(delta, input_vec)
        # 更新偏置项
        self.bias += rate * delta

    def forward(self, input_vecs, labels, rate):
        for input_vec, label in zip(input_vecs, labels):
            output = self.predict(input_vec)
            print(f"output:{output}")
            self._update_weights(input_vec, output, label, rate)
            print(f"self.weights:{self.weights}")

    def train(self, input_vecs, labels, iteration, rate):
        for i in range(iteration):
            print(f"iter:{i}")
            self.forward(input_vecs, labels, rate)


def f(x):
    """
    定义激活函数
    """
    return 1 if x > 0 else 0


def get_training_dataset():
    """
    基于and真值表构建训练数据
    """
    # 构建训练数据
    # 输入向量列表
    input_vecs = torch.tensor([[1,1], [0,0], [1,0], [0,1]], dtype=torch.float)
    # 期望的输出列表，注意要与输入一一对应
    # [1,1] -> 1, [0,0] -> 0, [1,0] -> 0, [0,1] -> 0
    labels = torch.tensor([1, 0, 0, 0], dtype=torch.float)
    return input_vecs, labels


def train_and_perceptron():
    """
    使用and真值表训练感知器
    """
    # 创建感知器、输惨参数个数为2，激活函数为f
    p = Perceptron(2, f)
    input_vecs, labels = get_training_dataset()
    p.train(input_vecs, labels, 10, 0.1)
    return p


if __name__ == '__main__':
    p = train_and_perceptron()
    input_vecs = torch.tensor([[1,1], [0,0], [1,0], [0,1]], dtype=torch.float)
    print(f"weight:{p.weights}, bias:{p.bias}")
    print(p.predict(input_vecs[0]))
    print(p.predict(input_vecs[1]))
    print(p.predict(input_vecs[2]))
    print(p.predict(input_vecs[3]))
